import React, { createContext, useContext, useEffect, useState } from 'react';
import type { ReactNode } from 'react';


// 定义主题类型
type Theme = 'default' | 'dark' | 'light' | 'blue';

// 定义上下文类型
interface ThemeContextType {
  theme: Theme;
  setTheme: (theme: Theme) => void;
  themes: Theme[];
}

// 创建上下文
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

// 主题列表
const THEMES: Theme[] = ['default', 'dark', 'light', 'blue'];

// 主题 Provider 组件
export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  // 从 localStorage 读取保存的主题，默认为 default
  const [theme, setTheme] = useState<Theme>(() => {
    const savedTheme = localStorage.getItem('app-theme');
    return savedTheme as Theme || 'default';
  });

  // 当主题变化时，更新 HTML 根元素类名并保存到 localStorage
  useEffect(() => {
    const root = document.documentElement;
    
    // 移除所有主题类名
    THEMES.forEach(t => root.classList.remove(`${t}-theme`));
    
    // 添加当前主题类名（默认主题不需要添加类名）
    if (theme !== 'default') {
      root.classList.add(`${theme}-theme`);
    }
    
    // 保存主题到本地存储
    localStorage.setItem('app-theme', theme);
  }, [theme]);

  return (
    <ThemeContext.Provider value={{ theme, setTheme, themes: THEMES }}>
      {children}
    </ThemeContext.Provider>
  );
};

// 自定义 Hook 方便使用主题上下文
export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (context === undefined) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};
